package org.crazyit.cloud.open;

import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;

/**
 * 断路器默认是关闭的，默认是10s20个请求
 */
public class OpenMain {

    public static void main(String[] args) {
        //先设置全局配置，
        ConfigurationManager
                .getConfigInstance()
                //这个属性从官网的wiki去查Default Property circuitBreaker.requestVolumeThreshold
                //10s内  10个请求，满足条件1
                .setProperty("hystrix.command.default.circuitBreaker.requestVolumeThreshold",
                        10);
        for (int i = 0; i < 15; i++) {
            ErrorCommand c = new ErrorCommand();
            c.execute();
            //输出断路器的状态
            System.out.println(c.isCircuitBreakerOpen());
        }
    }


    static class ErrorCommand extends HystrixCommand<String> {
        public ErrorCommand() {
            //一个命令超时时间设置成500ms
            super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
                    .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                            .withExecutionTimeoutInMilliseconds(500))
            );
        }

        @Override
        protected String run() throws Exception {
            //这里800大于设置的超时时间，所以命令总会执行回退
            Thread.sleep(800);
            return "success";
        }

        @Override
        protected String getFallback() {
            return "fallback";
        }
    }

}
